/*
 * This file Copyright (c) 2015. Walle.
 * (http://www.wallellen.com). All rights reserved.
 *
 *
 * This file is dual-licensed under both the
 * Walle Agreement (WA) and the GNU General Public License.
 * You may elect to use one or the other of these licenses.
 *
 * This file is distributed in the hope that it will be
 * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
 * Redistribution, except as permitted by whichever of the GPL
 * or WA you select, is prohibited.
 *
 * 1. For the GPL license (GPL), you can redistribute and/or
 * modify this file under the terms of the GNU General
 * Public License, Version 3, as published by the Free Software
 * Foundation.  You should have received a copy of the GNU
 * General Public License, Version 3 along with this program;
 * if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * 2. For the Walle Agreement (WA), this file
 * and the accompanying materials are made available under the
 * terms of the WA which accompanies this distribution, and
 * is available at http://www.wallellen.com/agreement.html
 *
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 */

/**
 *
 */
package com.wallellen.wechat.user;

import com.alibaba.fastjson.JSONObject;
import com.wallellen.core.http.HttpUtils;
import com.wallellen.wechat.exception.WeChatException;
import com.wallellen.wechat.token.TokenProxy;
import com.wallellen.wechat.util.WeChatUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URLEncoder;

/**
 * 账户管理
 *
 * @author <a href="mailto:wallellen@hotmail.com">WALLE</a>
 * @version 2015-7-5
 */
public class AccountManager {
    private static final Logger logger = LoggerFactory.getLogger(AccountManager.class);

    //长链接转短链接接口
    private static final String SHORTURL_POST_URL = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=";
    //生成带参数的二维码
    private static final String QRCODE_POST_URL = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=";
    //通过ticket换取二维码
    private static final String SHOWQRCODE_POST_URL = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=";
    private String accessToken;

    public AccountManager() {
        this.accessToken = TokenProxy.accessToken();
    }

    /**
     * 长链接转短链接接口
     *
     * @param longUrl 需要转换的长链接
     * @return
     */
    public String shortUrl(String longUrl) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("action", "long2short");
        jsonObject.put("long_url", longUrl);
        String requestData = jsonObject.toString();
        logger.info("request data " + requestData);
        String resultStr = HttpUtils.post(SHORTURL_POST_URL + this.accessToken, requestData);
        logger.info("return data " + resultStr);
        try {
            WeChatUtil.isSuccess(resultStr);
        } catch (WeChatException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return null;
        }
        JSONObject resultJson = JSONObject.parseObject(resultStr);
        return resultJson.getString("short_url");
    }

    /**
     * 创建永久二维码
     *
     * @param scene_id 场景值ID,目前参数只支持1--100000
     * @return
     */
    public Qrcode createQrcodePerpetual(long sceneId) {
        return createQrcodeTicket(QrcodeType.QR_LIMIT_SCENE, null, sceneId, null);
    }

    /**
     * 创建永久二维码
     *
     * @param scene_str 场景值ID,长度限制为1到64
     * @return
     */
    public Qrcode createQrcodePerpetualstr(String sceneStr) {
        return createQrcodeTicket(QrcodeType.QR_LIMIT_STR_SCENE, null, null, sceneStr);
    }

    /**
     * 创建临时二维码
     *
     * @param scene_id       场景值ID
     * @param expire_seconds 二维码有效时间，以秒为单位,最大不超过604800（即7天）。
     * @return
     */
    public Qrcode createQrcodeTemporary(long sceneId, int expireSeconds) {
        return createQrcodeTicket(QrcodeType.QR_SCENE, expireSeconds, sceneId, null);
    }

    private Qrcode createQrcodeTicket(QrcodeType qrcodeType, Integer expireSeconds, Long sceneId, String sceneStr) {
        JSONObject ticketJson = new JSONObject();
        ticketJson.put("action_name", qrcodeType);
        JSONObject sceneJson = new JSONObject();
        switch (qrcodeType) {
            case QR_SCENE:
                ticketJson.put("expire_seconds", expireSeconds);
                sceneJson.put("scene_id", sceneId);
                break;
            case QR_LIMIT_SCENE:
                sceneJson.put("scene_id", sceneId);
                break;
            case QR_LIMIT_STR_SCENE:
                sceneJson.put("scene_str", sceneStr);
                break;
        }
        JSONObject actionInfoJson = new JSONObject();
        actionInfoJson.put("scene", sceneJson);
        ticketJson.put("action_info", actionInfoJson);
        String requestData = ticketJson.toString();
        logger.info("request data " + requestData);
        String resultStr = HttpUtils.post(QRCODE_POST_URL + this.accessToken, requestData);
        logger.info("return data " + resultStr);
        try {
            WeChatUtil.isSuccess(resultStr);
        } catch (WeChatException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return null;
        }
        return JSONObject.parseObject(resultStr, Qrcode.class);
    }

    /**
     * 换取二维码
     *
     * @param ticket
     * @param qrcodeFile 二维码存储路径
     */
    public static void getQrcode(String ticket, String qrcodeFile) {
        try {
            byte[] b = HttpUtils.getFile(SHOWQRCODE_POST_URL + URLEncoder.encode(ticket, "UTF-8"));
            File file = new File(qrcodeFile);
            FileOutputStream fStream = new FileOutputStream(file);
            fStream.write(b);
            fStream.flush();
            fStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
